package com.eatme.web.app.article.job;

import com.eatme.web.app.article.service.ArticleService;
import com.eatme.web.sys.quartz.config.QuartzConfig;
import com.eatme.web.sys.quartz.service.IScheduleService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

@Component
public class PublishArticleJob extends QuartzJobBean {

    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    private static final Logger LOG = LoggerFactory.getLogger(PublishArticleJob.class);
    @Autowired
    private IScheduleService scheduleService;

    @Autowired
    private ArticleService articleServiceImpl;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Trigger trigger = jobExecutionContext.getTrigger();
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        Integer id = jobDataMap.getInt("data");
        LOG.debug("定时发布文章操作：{}",id);

        // 获取文章的 ID后获取文章，更新文章为发布的状态，还有发布的时间
        boolean success = articleServiceImpl.publishArticle(id);

        //完成后删除触发器和任务
        if (success) {
            LOG.debug("定时任务执行成功，开始清除定时任务");
            scheduleService.cancelScheduleJob(trigger.getKey().getName());
        }
    }
}
